package com.springboot.project.service.impl;

import com.springboot.project.dao.cluster.CityDao;
import com.springboot.project.dao.master.UserDao;
import com.springboot.project.domain.City;
import com.springboot.project.domain.User;
import com.springboot.project.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author liupenghui
 * @date 2018/7/10
 * @desc：
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User findByName(String userName) {

        // 从缓存中获取信息
        String key = userName;
        ValueOperations<String, User> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            LOGGER.info("从redis 读取信息");
            User user = operations.get(key);

           return user;
        }

        User user = userDao.findByName(userName);
        City city = cityDao.findByName("温岭市");
        user.setCity(city);
        LOGGER.info("从数据库读取信息");
        // 插入缓存
        operations.set(key, user, 10, TimeUnit.SECONDS);

        return user;
    }
}
